from Test import AbstractTest
import subprocess, signal
import os
import time
import sys

class bcolors:
    OKGREEN = '\033[92m'
    INF = '\033[90m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    HEAD = '\033[96m'

class TestSuite:
    def __init__(self, iServerCmd, iServerName):
        self.tests = []
        self.serverCmd = iServerCmd
        self.serverName = iServerName

    def print_ok(self, msg):
        print bcolors.OKGREEN + msg + bcolors.ENDC

    def print_info(self, msg):
    	print bcolors.INF + msg + bcolors.ENDC

    def print_header(self, msg):
		print bcolors.HEAD + msg +  bcolors.ENDC

    def print_fail(self, msg):
        print bcolors.FAIL + msg + bcolors.ENDC

    def run(self):
    	no = 1
    	suite_size = len(self.tests)
        for test in self.tests:
            self.print_header("[" + str(no) + "/" + str(suite_size) + "] Start = " + test.name())
            self.run_server()
            try:
                if test.run():
                    self.print_ok("[OK] " + test.name())
                else:
                    self.print_fail("[KO] " + test.name())
            except:
                 self.print_fail("[KO] " + test.name())
                 print "\t", sys.exc_info()
            self.stop_server()
            no = no + 1

    def run_server(self):
        os.system(self.serverCmd)
        # wait a while till it starts
        time.sleep(5)
       	self.print_info("Server Started.")

    def stop_server(self):
        p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
        out, err = p.communicate()
        for line in out.splitlines():
            if self.serverName in line:
                pid = int(line.split(None, 1)[0])
                os.kill(pid, signal.SIGKILL)
        # wait a while
        time.sleep(2)
        self.print_info("Server Stopped.")

    def add(self, test):
        self.tests.append(test)
